package com.itown.expo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import webframe.common.helper.MD5HashHelper;

import com.itown.expo.controller.base.MyBaseCommandController;
import com.itown.expo.model.EntUserInfo;

public class EntUserEditController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command) {
		EntUserInfo user = (EntUserInfo) command;
		List<EntUserInfo> list = getServiceContainer().getUserService()
				.findEntUserListByUsername(user.getUsername());
		Map<String, Object> map = new HashMap<String, Object>();

		if (user.getId() != null) {
			// modify
			if (list.size() == 1 && !list.get(0).getId().equals(user.getId())) {
				user.setErrorInfo("修改记录失败,此用户名和别的记录重复!");
				map.put("user", user);
				return new ModelAndView(getFailureView(), "map", map);
			}

			EntUserInfo ouser = list.get(0);
			ouser.setEntCname(user.getEntCname());
			ouser.setSimpleName(user.getSimpleName());
			ouser.setDeclRegNo(user.getDeclRegNo());
			ouser.setContactor(user.getContactor());
			ouser.setEmail(user.getEmail());
			ouser.setTelephone(user.getTelephone());
			ouser.setFax(user.getFax());
			ouser.setAddress(user.getAddress());
			ouser.setStatus(user.getStatus());
			getServiceContainer().getUserService().updateEntUser(ouser);
		} else {
			// create
			if (list.size() != 0) {
				user.setErrorInfo("添加新纪录失败,此用户名已存在!");
				map.put("user", user);
				return new ModelAndView(getFailureView(), "map", map);
			}
			user.setPassword(MD5HashHelper.hash("1234").toLowerCase());
			user.setRisk(0.0);
			user.setStatus(1L);
			user = getServiceContainer().getUserService().saveEntUser(user);
		}

		return new ModelAndView(new RedirectView("EntUserSearch.do?id="
				+ user.getId()), "map", map);
	}
}
